const db = require('../db')
const tool = require('../tools/tool')

module.exports = {
    async getList() {
        return {
            default: await db.select(`select * from categories`),
            fieldOnly: await tool.array.format(await db.select(`select * from categories`), (e) => {
                return e.name
            })
        }
    },
    async getInfo(id) {
        let re = await db.selectWithParams(`select * from categories where id = ?`, [id])
        if (!re.length) return undefined
        return re[0]
    },
    async delete(id) {
        if ((await db.selectWithParams(`select id from patrols where categoryId = ?`, [id])).length) throw '有相关巡查未删除'
        if ((await db.selectWithParams(`select id from permissions where type = 1 and categoryId = ?`, [id])).length) throw '有相关负责人未删除'
        if ((await db.selectWithParams(`select id from permissions where type = 2 and categoryId = ?`, [id])).length) throw '有相关审核人未删除'
        await db.deleteById('categories', id)
    },
    async update(id, name) {
        if ((await db.selectWithParams(`select * from categories where id != ? and name = ?`, [id, name])).length) throw '此名称已被使用'
        await db.updateById('categories', id, { name })
    },
    async add(name) {
        if ((await db.selectWithParams(`select * from categories where name = ?`, [name])).length) throw '此名称已被使用'
        await db.insertInto('categories', {
            name
        })
    }
}